import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './mybuy.scss'
import score from '../../assets/kedouimg01/vip3.png'
import lbicon from '../../assets/kedouimg01/lbicon.png'
import lbicon2 from '../../assets/kedouimg01/lbicon2.png'
import cat05 from '../../assets/kedouimg01/cat05.png'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id:'',
      discoun:'',
      shopId:'',
      payAmount:'',
      discountAmount:'',
      bl:'',//
      qunsf:'',//
      yhpri:"",
      qunjf:'',//
      paytype:1,
      zftype:0,
      paypwd:[],
      paypwdlen:0,
      tuitable:[{number:'1',tuibg:false,innerhtml:false,click:'1'},
                {number:'2',tuibg:false,innerhtml:false,click:'1'},
                {number:'3',tuibg:false,innerhtml:false,click:'1'},
                {number:'4',tuibg:false,innerhtml:false,click:'1'},
                {number:'5',tuibg:false,innerhtml:false,click:'1'},
                {number:'6',tuibg:false,innerhtml:false,click:'1'},
                {number:'7',tuibg:false,innerhtml:false,click:'1'},
                {number:'8',tuibg:false,innerhtml:false,click:'1'},
                {number:'9',tuibg:false,innerhtml:false,click:'1'},
                {number:'-',tuibg:true,innerhtml:false,click:'3'},
                {number:'0',tuibg:false,innerhtml:false,click:'1'},
                {number:'',tuibg:true,innerhtml:true,click:'2'}
              ],


      goodsIds:[],
      amounts:[],
      verificationCode:"",
      couponlist:[],
      yhqinfo:"无优惠券可用",
      member:{level:{discount:0}},
      dklist:[],
      dkarr:[],
      nodk:0,
      appmark:CommonJs.getmark()
    }
  }
  config = {
    navigationBarTitleText: '我要买单'
  }

  componentWillMount () {
   	if(this.$router.preload){
   		if(this.$router.preload.cindex>=0){

   		}
   		else{
	  		this.setState({
	  			id:this.$router.preload.id,
				  discount:this.$router.preload.discountAmount,
				  shopId:this.$router.preload.shopId,
				  payAmount:this.$router.preload.payAmount,
				  discountAmount:this.$router.preload.discountAmount,
				  bl:this.$router.preload.bl,
				  qunsf:parseFloat(this.$router.preload.payAmount),
				  yhpri:parseFloat(this.$router.preload.payAmount),
				  qunjf:parseFloat((this.$router.preload.payAmount-this.$router.preload.discountAmount)*this.$router.preload.bl/100)
	  		})

	  		if(this.$router.preload.goodsIds){
	  			this.setState({
	  				goodsIds:this.$router.preload.goodsIds.join(','),
				  	amounts:this.$router.preload.amounts.join(',')
				  })

	  		}

	  		this.getcoupon(this.$router.preload.payAmount,this.$router.preload.shopId)
	  		
	  	}
		}
   	
  }
	componentDidShow () {
		var cindex="";
		var pages = getCurrentPages();
		var Page = pages[pages.length - 1];
		var info = Page.data;
		if(info.data){
			cindex=info.data.cindex;
			var list=this.state.couponlist;
			var yj=this.state.yhpri;
			var totalAmount=this.state.payAmount;
			var jg=this.getyhpri(list[cindex].couponType,list[cindex].ruleFavourData,list[cindex].ruleLimitData,totalAmount);
			var str="-"+jg
			if(yj>jg){
				var sf=yj-jg;
			}
			else{
				sf=0;
			}
			this.setState({
				yhqinfo:str,
				verificationCode:list[cindex].verificationCode,
				qunsf:sf
			})
		}
	}
  payment(paytype){
  	this.setState({
			paytype:paytype
		})
  }
  getmember(){
  	var url='/shop/papi/v1.9/members/account/'+Taro.getStorageSync('shopId')
  	var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){
       var qunsf=_this.state.qunsf;
    	 if(res.data){
    	 	 qunsf=qunsf*res.data.level.discount/100
	       _this.setState({
	          member:res.data,
	          qunsf:qunsf
	        });
	        _this.getdklist(qunsf*100)
	     }
    	 else{
    	 	 _this.getdklist(qunsf*100)
    	 }
    },'wfw')
  }
  getcode(){
    // console.log('111111111111111111111111111111111111111111')
    var _this = this
    var paytype = _this.state.paytype
    if (paytype == 1) {
      Taro.login({
        success(res) {
          // console.log(JSON.stringify(res)+'aa1111')
          if (res.code) {
            _this.submits(res.code)
          } else {
            Taro.showToast({
              title:'网络异常',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else if (paytype == 2||paytype==12) {
      _this.submits('')
    }
  }
  getcoupon(totalAmount,shopId){
  	var url="/verify/papi/v1.9/consumption-order/couponForOrder";
  	var dates={
  		totalAmount:totalAmount,
  		shopId:shopId
  	}
  	var _this=this
  	CommonJs.ajaxRequest(url,dates,'POST',function(res){
  		if(res.data.length>0&&res.data[0].useable){
  			var str="最高减"+_this.getyhpri(res.data[0].couponType,res.data[0].ruleFavourData,res.data[0].ruleLimitData,totalAmount)+"元"
  			_this.setState({
				yhqinfo:str,
				couponlist:res.data
			})
  		}
  		_this.getmember()
  	},'wfw')
  }
  getyhpri(type,ruleFavourData,ruleLimitData,totalAmount){
  	var md=ruleLimitData/100
  	if(type.indexOf('QUOTA')==0){
			var je=ruleFavourData/100
		}
		else if(type.indexOf('CONSUPTION_QUOTA')==0){
			var je=ruleFavourData/100
		}
		else if(type.indexOf('CONSUPTION_DISCOUNT')==0){
			var je=(100-ruleFavourData)/100*totalAmount;

		}
		else if(type.indexOf('COUNT_DISCOUNT')==0){
			var je=(100-ruleFavourData)/100*totalAmount;
		}
		else{

			var je=parseInt(totalAmount/md)*(ruleFavourData/100);

		}
		return je.toFixed(2);
  }
  open(url,type){
    CommonJs.openTo(url)
  }
  chooseyhq(){
  	this.$preload({
	  	byfrom:'mybuy',
	  	payAmount:this.$router.preload.payAmount*100,
	  	shopId:this.$router.preload.shopId
		})
  	this.open("/pages/coupon/coupon");
  }
  submits(code){
  	var _this=this
    var date
  	var storeId = _this.state.shopId
    var totalAmount = _this.state.payAmount
    var amount = _this.state.discountAmount
    var payOffId = _this.state.id
    var payAmounts= _this.state.qunsf
    var paytype = _this.state.paytype
	  date = {
	      shopId:storeId,
	      totalAmount:totalAmount*100,
	      amount:amount,
	      payAmount:payAmounts*100,
	      payTypeId:125,
	      code: code
	    }
    if (paytype == 1) {//微信
      if (payOffId == '') {

      }
      else {
      	date.payOffId=payOffId
      }
      _this.pay(date)
	  }
	  else if (paytype == 2 || paytype == 12) {//资金账号
	  	if(payAmounts==0){
	  		_this.pay(date)
	  	}
	  	else{
		  	_this.setState({
	        zftype:1,
	        paypwd:[],
	        paypwdlen:0
	      })
		  }
	  }
  }
  pay(date){
    var _this=this
    if(this.state.goodsIds.length>0){
    	date.goodsIds=this.state.goodsIds;
    	date.amounts=this.state.amounts;

    }
    if(this.state.verificationCode){
    	date.verificationCode=this.state.verificationCode
    }
    var dkarr=this.state.dkarr;
    var parr=[];
    if(dkarr.length>0){
    	for(var i=0;i<dkarr.length;i++){
    		var obj={
    			"payTypeId": dkarr[i]
    		}
    		parr.push(obj)
    	}
    	date.orderDeductionList=parr
    }
    console.log(JSON.stringify(date)+"//4444")
    Taro.showLoading({title: '支付中'})
	var url='/verify/papi/v1.9/consumption-order/createPay';
    CommonJs.ajaxRequest(url,date,'POST',function(res){
      // console.log(JSON.stringify(res)+"//55555")
      Taro.hideLoading()
      var paytype = _this.state.paytype
      if (paytype == 1) {
        if(date.payAmount>0){
		  		res=res.data;
		  		//console.log(res.appId+"//"+res.timeStamp+"//"+res.nonceStr+"//"+res.packageValue+"//"+res.signType+"//"+res.paySign)
          Taro.requestPayment({
          	appId:res.appId,
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.packageValue,
            signType: res.signType,
            paySign: res.paySign,
            success(res) {
              CommonJs.open('/pages/my/consumer')
            },
            fail(res) {
            	//console.log(JSON.stringify(res)+"2221")
              Taro.showToast({
                title:'支付失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
        else{
        	 CommonJs.open('/pages/my/consumer')
        }
      }
	  else if (paytype == 2||paytype == 12) {
        if (res.code != 300) {
          Taro.showModal({
            title:'支付结果',
            content:'支付成功！请把验证码给商家验码',
            showCancel:false,
            success(ret){
              if(ret.confirm){
                _this.setState({
                  zftype:0
                },function(){
                  CommonJs.open('/pages/my/consumer')
                })
              }
            }
          })
        } else {
          Taro.showModal({
            title:'支付失败',
            content:res.msg,
            showCancel:false,
            confirmText:'重试',
            success(ret){
              if(ret.confirm){
                _this.setState({
                  paypwd:[],
                  paypwdlen:0
                })
              }
            }
          })
        }
      }
    },'wfw')
  }
  buzhichi(){
//  Taro.showModal({
//    title: '提示',
//    content: '抱歉，小程序不允许你访问网页链接，如需获得最全功能和更好体验请下载“蝌蚪社区”APP!',
//    showCancel: false
//  })
		CommonJs.openTo('/pages/my/pwdset')
	
  }
  closepay(){
    this.setState({
      zftype:0
    })
  }
  inputNum(type,event){
    var _this = this
    var paypwd = _this.state.paypwd
    if (type == 1) {
      var paypwdlen = paypwd.length
      if (paypwdlen < 6) {
        var num = event.target.dataset.number
        paypwd.push(num)
        var paypwdlen = paypwd.length
        _this.setState({
          paypwd:paypwd,
          paypwdlen:paypwdlen
        },function(){
          if (paypwdlen == 6) {
            var date
            var storeId = _this.state.shopId
            var totalAmount = _this.state.payAmount
            var amount = _this.state.discountAmount
            var payOffId = _this.state.id
            var payAmounts= _this.state.qunsf
            var payPasswords = _this.state.paypwd
            var payPassword = payPasswords.join('');
            var payTypeId;
            if(_this.state.paytype==2){
            	payTypeId=10;
            }
            else{
            	payTypeId=12;
            }
            date = {
                shopId:storeId,
                totalAmount:totalAmount*100,
                amount:amount*100,
                payAmount:payAmounts*100,
                payTypeId:payTypeId,
                payOffId:payOffId,
                payPassword: payPassword
              }
           
            _this.pay(date)
          }
        })
      }
    } else if (type == 2) {
      paypwd.pop()
      var paypwdlen = paypwd.length
      _this.setState({
        paypwd:paypwd,
        paypwdlen:paypwdlen
      })
    }
    // console.log(JSON.stringify(_this.state.paypwd))
  }
  getdklist(payAmount){
  	var userid=Taro.getStorageSync('dateinfo').userid
  	var url="/order/papi/v1.9/pay/deductionMethod/"+userid+"/"+parseInt(payAmount)
  	var _this=this
  	CommonJs.ajaxRequest(url,'','GET',function(res){ 
  		var red=res.data;
  		var qunsf=payAmount;
  		var dkarr=_this.state.dkarr;
  		var nodk=payAmount;
  		for(var i=0;i<red.length;i++){
  			if(red[i].deductionAmount>0){
  				dkarr.push(red[i].payTypeId)
  				qunsf=qunsf-red[i].deductionAmount
  			}
  		}
  		if(qunsf<0){
  			qunsf=0
  		}
  		_this.setState({
				dklist:res.data,
				qunsf:qunsf/100,
				dkarr:dkarr,
				nodk:nodk
			})
  	},'wfw')
  }
  dotype(id){
  	if(id==211){
  		if(CommonJs.getmark()=='xjzb'){
  			return '共享金'
  		}
  		else{
  			return '收益金'
  		}
  	}
  	else{
  		return '消费金'
  	}
  }
  dkchoose(index,id){
  	var dkarr=this.state.dkarr;
  	var qunsf=this.state.qunsf;
  	var dklist=this.state.dklist;
  	var nodk=this.state.nodk;
  	if(dkarr.indexOf(id)>=0){
  		dkarr.splice(dkarr.indexOf(id),1)
  	}
  	else{
  		dkarr.push(id)
  	}
  	qunsf=nodk
  	for(var i=0;i<dkarr.length;i++){
  		for(var j=0;j<dklist.length;j++){
  			if(dkarr[i]==dklist[j].payTypeId){
  				qunsf=qunsf-dklist[j].deductionAmount
  			}
  		}
  	}
  	if(qunsf<0){
  		qunsf=0
  	}
  	this.setState({
			qunsf:qunsf/100,
			dkarr:dkarr
		})
  }
  render () {
	  const tuitable = this.state.tuitable
	  const member=this.state.member
	  const dklist=this.state.dklist
    return (
      <View className='page'>
        <View className='qun-zffixed' style={this.state.zftype == 1 ? 'display:block;' : 'display:none;'}>
          <View className='qun-zfbotn'>
            <View className='section'>
              <View className='qun-zftite'>
                <Image className='qun-zfclose' onClick={this.closepay.bind(this)} src="https://minichat.g2ma.com/kedouimg/close1.png"></Image>
                <Text>请输入支付密码</Text>
                <Text></Text>
              </View>
              <View className='qun-zfmima'>
                <View className='qun-zfkuan'>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 1 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 2 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 3 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 4 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 5 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 6 ? '●' : ''} type='text' disabled='true'/>
                </View>
              </View>
              <View className='qun-zfwanji'><Text onClick={this.buzhichi.bind(this)}>忘记密码?</Text></View>
              <View className='tui-table-view'>
                {tuitable.map((item, index) => (
                  <View className={item.tuibg ? 'tui-col-3 tui-bg' : 'tui-col-3'} dataNumber={item.number} onClick={this.inputNum.bind(this,item.click)}>
                  {item.innerhtml ?
                    <Image className='qun-zfdel' src='https://minichat.g2ma.com/kedouimg/del.png'></Image>
                    :
                    item.number
                  }
                  </View>
                ))}
              </View>
            </View>
          </View>
        </View>
        <View className="qunul">
          <View className="qunli">
            <Text className="qunjea">买单金额</Text>
            <Text className="qunjeb payAmount">￥{this.state.payAmount}</Text>
          </View>
          <View className="qunli" style="display:none">
            <Text className="qunjea">不参与优惠的金额</Text>
            <Text className="qunjeb discount">-{this.state.discount}</Text>
          </View>
          <View className="qunli" onClick={this.chooseyhq.bind(this)}>
            <Image mode="scaleToFill" className='yhqjt' src="https://minichat.g2ma.com/kedouimg/goselect.png"></Image>
            <Text className="qunjea">优惠券</Text>
            <Text className="qunjeb yhqjf">{this.state.yhqinfo}</Text>

          </View>
          <View className="qunli" style={member.id?'':'display:none;'}>
            <Text className="qunjea">会员折扣({member.level.discount/100}折)</Text>
            <Text className="qunjeb qunsf">-{(this.state.payAmount*(1-member.level.discount/100)).toFixed(2)}</Text>
          </View>
          
          <View className="qunli" style="display:none;">
            <Text className="qunjea">实付金额</Text>
            <Text className="qunjeb qunsf">￥{this.state.qunsf}</Text>
          </View>
          <View className="qunli" style="display:none">
            <Text className="qunjea">获得{this.state.appmark=='xjzb'?'WUC':'积分'}数量</Text>
            <Text className="qunjeb qunjf">{this.state.qunjf}</Text>
          </View>

        </View>
        <View className='dk-box' style={dklist&&dklist.length>0?'':"display:none"} >
        	{dklist.map((item, index) => (
        	<View className='dk-dl' style={item.deductionAmount>0?'':"display:none"} onClick={this.dkchoose.bind(this,index,item.payTypeId)}>
        		<View className='dk-dt'><Image mode='widthFix' className='img' src={score}></Image></View>
        		<View className='dk-dd'>可用{item.deductionAmount/100}{this.dotype(item.payTypeId)}抵用{item.deductionAmount/100}费用</View>
        		<View className='dk-dds'><Image mode='widthFix' className='img' src={this.state.dkarr.indexOf(item.payTypeId)>=0?lbicon:lbicon2}></Image></View>
        	</View>
        	))}
        	
        </View>
        <View className='qun-bgbanner'>
          <View className='qun-sohofs'>
            <View className='qun-pkzhifu'>支付方式</View>
            <View className='qun-bmgue' onClick={this.payment.bind(this,1)}>
              <View classNme='qun-zifans'>
                <View className='qun-zifuli'>
                  <View className='qun-fasi'>
                    <Image mode="scaleToFill" className='qun-fsimg' src="https://minichat.g2ma.com/kedouimg/icon26.png"></Image>
                    <View className='qun-wexm'>
                      <Text>微信支付</Text>
                    </View>
                  </View>
                  <Image className='qun-bmbgtu'  src={this.state.paytype==1?'https://minichat.g2ma.com/kedouimg/icon24.png':'https://minichat.g2ma.com/kedouimg/icon23.png'}></Image>
                </View>
              </View>
            </View>
            <View className='qun-bmgue' onClick={this.payment.bind(this,2)}>
              <View classNme='qun-zifans'>
                <View className='qun-zifuli'>
                  <View className='qun-fasi'>
                    <Image mode="scaleToFill" className='qun-fsimg' src="https://minichat.g2ma.com/kedouimg/icon28.png"></Image>
                    <View className='qun-wexm'>
                      <Text>余额支付</Text>
                    </View>
                  </View>
                  <Image className='qun-bmbgtu'  src={this.state.paytype==2?'https://minichat.g2ma.com/kedouimg/icon24.png':'https://minichat.g2ma.com/kedouimg/icon23.png'}></Image>
                </View>
              </View>
            </View>
            <View className='qun-bmgue' onClick={this.payment.bind(this,12)} style={this.state.appmark=='xjzb'?'':'display:none'}>
              <View classNme='qun-zifans'>
                <View className='qun-zifuli'>
                  <View className='qun-fasi'>
                    <Image mode="scaleToFill" className='qun-fsimg' src={cat05}></Image>
                    <View className='qun-wexm'>
                      <Text>UC支付</Text>
                    </View>
                  </View>
                  <Image className='qun-bmbgtu'  src={this.state.paytype==12?'https://minichat.g2ma.com/kedouimg/icon24.png':'https://minichat.g2ma.com/kedouimg/icon23.png'}></Image>
                </View>
              </View>
            </View>
          </View>
          <View className='qun-gmbom'>
            <View className='qun-gmyfje'>
              付款金额: ￥
              <Text className='qun-gmcol'>{this.state.qunsf?this.state.qunsf.toFixed(2):0}</Text>
            </View>
            <View className='qun-gmtjdd' onClick={this.getcode.bind(this)}>确定</View>
          </View>
        </View>
      </View>
    )
  }
}
